package com.icode.pool;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-12 22:20
 */
public class Test1 {

    public static void main(String[] args) {

        //创建一个使用从无界队列运行的单个工作线程的执行程序。
        ExecutorService service1 = Executors.newSingleThreadExecutor();

        //创建一个线程池，该线程池重用固定数量的从共享无界队列中运行的线程。
        ExecutorService service2 = Executors.newFixedThreadPool(10);

        //创建一个根据需要创建新线程的线程池，但在可用时将重新使用以前构造的线程
        ExecutorService service3 = Executors.newCachedThreadPool();

        try {
            for (int i = 0; i < 20; i++) {
                service1.execute(() -> {
                    System.out.println("一条线程：" + Thread.currentThread().getName());
                });
            }
            TimeUnit.SECONDS.sleep(2);
            System.out.println("----------------");

            for (int i = 0; i < 20; i++) {
                service2.execute(() -> {
                    System.out.println("固定线程池：" + Thread.currentThread().getName());
                });
            }
            TimeUnit.SECONDS.sleep(2);
            System.out.println("----------------");


            for (int i = 0; i < 100; i++) {
                service3.execute(() -> {
                    System.out.println("动态线程池：" + Thread.currentThread().getName());
                });
            }
            TimeUnit.SECONDS.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            service1.shutdown();
            service2.shutdown();
            service3.shutdown();
        }

    }
}
